
//链表逆置
public class ListNode {
    int val;
    ListNode next;
 
    ListNode(int v) {
        this.val = v;
    }


 

    //链表翻转
    public ListNode reserveList(ListNode head) {
        //判空
        if (head == null) {
            return null;
        }
        //只有一个节点的情况
        if (head.next == null) {
            return head;
        }
        //记录当前位置和它的前一个位置
        ListNode cur = head;
        ListNode prev = null;
        ListNode newHead = null;//用来保存头结点
        while (cur != null) {
            ListNode next = cur.next;
            if (next == null) {
                newHead = cur;
            }
            //逆置 核心操作
            cur.next = prev;
            //更新
            prev = cur;
            cur = next;
        }
        return newHead;
    }
}
